package com.onpositive.data.serializer.writers;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import com.onpositive.data.serializer.readers.DefaultReaderFactory;
import com.onpositive.data.units.DateWithAccuracy;
import com.onpositive.datamap.values.impl.DateRange;

public class RangedDateWriter extends AbstractWriter<DateRange>{

	public RangedDateWriter() {
		super( DateRange.class );
	}

	DateWithAccuracyWriter lows=new DateWithAccuracyWriter();
	DateWithAccuracyWriter highs=new DateWithAccuracyWriter();
	StringWriter strs=new StringWriter();
	
	@Override
	public void append(DateRange value) {
		if( value == null ){
			lows.append(null);
			highs.append(null);
			strs.append(null) ;
			return ;
		}
		DateWithAccuracy low = value.getLow();		
		DateWithAccuracy high = value.getHigh();
		
		if (low == high) {
			lows.append( null );
			highs.append(high);
		} else {
			lows.append(low);
			highs.append(high);
		}
		
		Object comment = value.getComment();
		strs.append(comment == null ? null : comment.toString());
	}

	@Override
	protected int getID() {
		return DefaultReaderFactory.RW_ID_DATE_RANGE;
	}

	@Override
	protected void doSerialize() {
		try{
		ByteArrayOutputStream sm=new ByteArrayOutputStream();
		DataOutputStream stream2 = new DataOutputStream(sm);
		lows.serialize(stream2);
		int s0=stream2.size();
		highs.serialize(stream2);
		int s1=stream2.size();
		strs.serialize(stream2);
		int s2=stream2.size();
		stream2.close();
		stream.writeInt(s0);
		stream.writeInt(s1);
		stream.writeInt(s2);
		stream.write(sm.toByteArray());
		}catch (IOException e) {
			throw new IllegalStateException(e);
		}
	}

}
